package com.kc.gb.device.configurations.support;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

@Slf4j
public class RequestResponseLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        // 包装请求，允许多次读取请求体
        ContentCachingRequestWrapper requestWrapper =
                new ContentCachingRequestWrapper((HttpServletRequest) request);

        // 包装响应，允许多次读取响应体
        ContentCachingResponseWrapper responseWrapper =
                new ContentCachingResponseWrapper((HttpServletResponse) response);

        // 继续处理请求
        chain.doFilter(requestWrapper, responseWrapper);

        // 记录请求信息
        logRequest(requestWrapper);

        // 记录响应信息
        logResponse(requestWrapper,responseWrapper);

        // 将响应内容写回原始响应
        responseWrapper.copyBodyToResponse();
    }

    private void logRequest(ContentCachingRequestWrapper request) {
        if (request.getContentLength() > 0) {
            String requestBody = new String(request.getContentAsByteArray());
            log.info("Request url: {}", request.getRequestURI().toString());
        }
    }

    private void logResponse(ContentCachingRequestWrapper request,ContentCachingResponseWrapper response) {
        if (response.getContentSize() > 0) {
            try {
                String responseBody = new String(response.getContentAsByteArray(), response.getCharacterEncoding());
                log.info("Response URI:{} status:{}" ,request.getRequestURI(),response.getStatus());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
